def load_dataset(file_path):
    dataset = []
    with open(file_path, 'r') as file:
        for line in file:
            dataset.append(line.strip().split(','))
    return dataset

def create_c1(dataset):
    c1 = []
    for transaction in dataset:
        for item in transaction:
            if not [item] in c1:
                c1.append([item])
    c1.sort()
    return list(map(frozenset, c1))

def scan_d(d, candidates, min_support):
    sscnt = {}
    for tid in d:
        for can in candidates:
            if can.issubset(tid):
                sscnt[can] = sscnt.get(can, 0) + 1
    num_items = float(len(d))
    retlist = []
    support_data = {}
    for key in sscnt:
        support = sscnt[key] / num_items
        if support >= min_support:
            retlist.insert(0, key)
        support_data[key] = support
    return retlist, support_data

def apriori_gen(lk, k):
    retlist = []
    lenlk = len(lk)
    for i in range(lenlk):
        for j in range(i+1, lenlk):
            l1 = list(lk[i])[:k-2]
            l2 = list(lk[j])[:k-2]
            l1.sort()
            l2.sort()
            if l1 == l2:
                retlist.append(lk[i] | lk[j])
    return retlist

def apriori(dataset, min_support=0.5):
    c1 = create_c1(dataset)
    d = list(map(set, dataset))
    l1, support_data = scan_d(d, c1, min_support)
    l = [l1]
    k = 2
    while (len(l[k-2]) > 0):
        ck = apriori_gen(l[k-2], k)
        lk, sup_k = scan_d(d, ck, min_support)
        support_data.update(sup_k)
        l.append(lk)
        k += 1
    return l, support_data

# 用于打印频繁项集和它们的支持度
def print_frequent_itemsets(l, support_data, min_support):
    result = []
    for i in range(1, len(l)):
        for freq_set in l[i]:
            support = support_data[freq_set]
            if support >= min_support:
                result.append((freq_set, support))
    return result

# 测试数据集
if __name__ == "__main__":
    file_path = 'GroceryStoreDataSet.csv'
    dataset = load_dataset(file_path)
    l, support_data = apriori(dataset, min_support=0.1)
    frequent_itemsets = print_frequent_itemsets(l, support_data, 0.1)
    for itemset, support in frequent_itemsets:
        print(f"Frequent {len(itemset)}-itemset: {set(itemset)}, support: {support}")